<template>
	<view>
		<!-- 已登录内容 -->
		<block>
			<!-- 固定底部导航栏 -->
			<tnTabbar :currentIndex="currentTabIndex"></tnTabbar>

			<!-- 顶部栏 -->
			<view class="header-bar">
				<view class="header-title">消息</view>
			</view>

			<!-- 消息列表 -->
			<view class="content-container">
				<view v-if="chatList.length === 0" class="empty-state">
					<text>暂无消息</text>
				</view>
				<view v-else class="message-list">
					<view v-for="(chat, index) in chatList" :key="index" class="chat-item" @tap="handleChatClick(chat)">
						<image class="avatar" :src="chat.partnerAvatar || '/static/images/default-avatar.png'" />
						<view class="content">
							<view class="header">
								<text class="name">{{chat.partnerName || '用户' + chat.partnerId}}</text>
								<text class="time">{{formatTime(chat.updateTime)}}</text>
							</view>
							<view class="message">
								<text class="text">{{chat.lastMessage || '暂无消息'}}</text>
								<view v-if="chat.unreadCount > 0" class="badge">{{chat.unreadCount}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	import messageApi from '@/utils/api.js';

	export default {
		name: "MessageList",
		data() {
			return {
				currentTabIndex: 3,
				chatList: [],
				isLoggedIn: false
			};
		},
		onShow() {
			this.checkLoginStatus();
			if (this.isLoggedIn) {
				this.loadChatList();
			}
		},
		methods: {
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				const userInfo = uni.getStorageSync('userInfo');
				this.isLoggedIn = !!(token && userInfo);

				// 如果用户未登录，清空聊天列表
				if (!this.isLoggedIn) {
					this.chatList = [];
				}
			},

			async loadChatList() {
				try {
					const userInfo = uni.getStorageSync('userInfo');
					if (userInfo===undefined ||userInfo.id===undefined) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return; 
					}

					const res = await messageApi.getChatList();

					if (res.data.errno === 0) {
						// 对会话列表进行去重处理
						const uniqueChats = [];
						const seenPartners = new Set();

						res.data.data.forEach(chat => {
							if (!seenPartners.has(chat.partnerId)) {
								seenPartners.add(chat.partnerId);
								uniqueChats.push(chat);
							}
						});

						// 按更新时间排序
						uniqueChats.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime));

						this.chatList = uniqueChats;
					}
				} catch (error) {
					console.error('加载聊天列表失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},

			formatTime(time) {
				if (!time) return '';

				try {
					const date = new Date(time);

					// 格式化为 yyyy-MM-dd HH:mm:ss
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');

					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				} catch (error) {
					console.error('时间格式化错误:', error);
					return '';
				}
			},

			handleChatClick(chat) {
				if (!chat.partnerId) {
					console.error('无效的聊天对象:', chat);
					uni.showToast({
						title: '无效的聊天对象',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: '/pages/message/ChatDetail',
					success: function(res) {
						res.eventChannel.emit('chatInfo', {
							sellerId: chat.partnerId,
							sellerName: chat.partnerName,
							sellerAvatar: chat.partnerAvatar,
							productId: chat.productId
						});
					},
					fail: function(err) {
						console.error('跳转失败:', err);
						uni.showToast({
							title: '跳转失败',
							icon: 'none'
						});
					}
				});
			},

			// 在登录成功后调用
			onLoginSuccess() {
				this.checkLoginStatus();
				if (this.isLoggedIn) {
					this.loadChatList();
				}
			},

			updateChatSession(chatInfo) {
				// 查找是否已存在该会话
				const index = this.chatList.findIndex(chat => chat.partnerId === chatInfo.partnerId);

				if (index !== -1) {
					// 更新已存在的会话
					this.chatList[index] = {
						...this.chatList[index],
						lastMessage: chatInfo.lastMessage,
						updateTime: chatInfo.updateTime,
						productId: chatInfo.productId
					};

					// 将更新的会话移到顶部
					const updatedChat = this.chatList.splice(index, 1)[0];
					this.chatList.unshift(updatedChat);
				} else {
					// 添加新会话到顶部
					this.chatList.unshift(chatInfo);
				}

				// 重新加载会话列表以保持同步
				this.loadChatList();
			}
		}
	};
</script>

<style>
	.header-bar {
		padding: 10px 10px 10px;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}

	.header-title {
		font-size: 18px;
		font-weight: bold;
	}

	.content-container {
		height: calc(100vh - 100px);
		background-color: #f5f5f5;
	}

	.empty-state {
		text-align: center;
		padding: 40px;
		color: #999;
	}

	.message-list {
		padding: 10px 0;
	}

	.chat-item {
		display: flex;
		padding: 15px;
		background-color: #fff;
		border-bottom: 1px solid #f5f5f5;
	}

	.avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		border: 1px solid #eee;
		margin-right: 12px;
	}

	.content {
		flex: 1;
		overflow: hidden;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 6px;
	}

	.name {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}

	.time {
		font-size: 12px;
		color: #999;
	}

	.message {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.text {
		font-size: 14px;
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.badge {
		background-color: #ff4400;
		color: white;
		font-size: 12px;
		min-width: 18px;
		height: 18px;
		border-radius: 9px;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 5px;
		margin-left: 5px;
	}
</style>